package com.example.yichuangyun.utils;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.core.content.FileProvider;

import com.example.yichuangyun.application.MyApplication;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.ui.activity.LoginActivity;
import com.example.yichuangyun.ui.activity.MainActivity;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtil {
    // 两次点击按钮之间的点击间隔不能少于800毫秒
    private static final int MIN_CLICK_DELAY_TIME = 800;
    private static long lastClickTime;

    public static boolean isCanClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    /**
     * 隐藏软键盘
     */
    public static void closeKeyboard(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && activity.getCurrentFocus() != null) {
            if (activity.getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 检查是否登录
     */
    public static boolean isLogin(Context context) {
        if (!MyApplication.manager.isLogin()) {
            Intent intent = new Intent(context, LoginActivity.class);
            context.startActivity(intent);
            return false;
        }
        return true;
    }

    public static void jumpToLogin(Activity activity) {
        MyApplication.manager.clearUserInfo();
        MyApplication.getInstance().popAllActivityExceptOne();
        MyApplication.getInstance().exit();
        JumpIntent.jump(activity, LoginActivity.class);
    }

    public static void jumpToMain(Activity activity) {
        MyApplication.getInstance().popAllActivityExceptOne();
//        MyApplication.getInstance().exit();
        JumpIntent.jump(activity, MainActivity.class);
    }


    /**
     * 裁剪图片方法实现
     */
    public static void setIntent(Intent intent, Uri uri, Uri imageUri) {
        intent.setDataAndType(uri, "image/*");
        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // 去黑边
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        // aspectX aspectY 是宽高的比例，根据自己情况修改
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高像素
        intent.putExtra("outputX", 400);
        intent.putExtra("outputY", 400);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        //取消人脸识别功能
        intent.putExtra("noFaceDetection", true);
        //设置返回的uri
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        //设置为不返回数据
        intent.putExtra("return-data", false);
    }

    public static String checkText(String s) {
        if (TextUtils.isEmpty(s)) {
            return "";
        }
        return s;
    }

    public static String setText(String s) {
        if (TextUtils.isEmpty(s)) {
            return "/";
        }
        return s;
    }

    public static String setText2(String s) {
        if (TextUtils.isEmpty(s)) {
            return "暂无数据";
        }
        return s;
    }

    public static String setText3(String s) {
        if (TextUtils.isEmpty(s)) {
            return "--";
        }
        return s;
    }

    public static String setYHMTime(String s) {
        if (TextUtils.isEmpty(s) || s.equals("暂无")) {
            return "/";
        }
        if (s.length() > 10) {
            return s.substring(0, 10);
        }
        return s;
    }

    public static void installAPK(Context context, String apkPath) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //版本在7.0以上是不能直接通过uri访问的
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            File file = (new File(apkPath));
            // 由于没有在Activity环境下启动Activity,设置下面的标签
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(context, Constant.APP_PROVIDER, file);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(new File(apkPath)),
                    "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    /**
     * 获取文件path
     *
     * @param context 上下文
     * @param uri     uri
     * @return path
     */
    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver()
                    .query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
     * 6-18位数字和字母组成的密码
     */
    public static boolean checkPassword(String password) {
        String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$";
        return password.matches(regex);
    }

    public static boolean isEmail(String email) {
        if (null == email || "".equals(email)) return false;
        //Pattern p = Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}"); //简单匹配
        Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");//复杂匹配
        Matcher m = p.matcher(email);
        return m.matches();
    }

    public static String getDistance(double s) {
        if (s > 1000) {
            s = Math.round(s / 100d) / 10d; // 单位：千米 保留一位小数
            return s + "km";
        }
        return Math.round(s) + "m";
    }

    // 地球半径
    private static final double EARTH_RADIUS = 6378.137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 根据两个地点的经纬度计算距离，返回单位是:千米
     */
    public static String getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {
        double Lat1 = rad(latitude1);
        double Lat2 = rad(latitude2);
        double a = Lat1 - Lat2;
        double b = rad(longitude1) - rad(longitude2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(Lat1) * Math.cos(Lat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS; // 有小数的情况;注意这里的10000d中的“d”
        s = Math.round(s * 10000d) / 10000d;
        s = s * 1000; // 单位：米
        //        s = Math.round(s/10d) /100d; // 单位：千米 保留两位小数
        if (s > 1000) {
            s = Math.round(s / 100d) / 10d; // 单位：千米 保留一位小数
            return s + "km";
        }
        return Math.round(s) + "m";
    }

    /**
     * 计算给定经纬度周围一公里范围内的经纬度范围
     */
    public static Map<String, Double> calculateBoundingBox(double centerLatitude, double centerLongitude) {
        double latitudeDelta = 0.009; // 大约相当于一公里的纬度差
        double longitudeDelta = 0.009 / Math.cos(Math.toRadians(centerLatitude)); // 考虑纬度对经度的影响

        double minLatitude = centerLatitude - latitudeDelta;
        double maxLatitude = centerLatitude + latitudeDelta;
        double minLongitude = centerLongitude - longitudeDelta;
        double maxLongitude = centerLongitude + longitudeDelta;

        Map<String, Double> boundingBox = new HashMap<>();
        boundingBox.put("minLatitude", minLatitude);
        boundingBox.put("maxLatitude", maxLatitude);
        boundingBox.put("minLongitude", minLongitude);
        boundingBox.put("maxLongitude", maxLongitude);

        return boundingBox;
    }

    public static void copyText(Context context, String text) {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData mClipData = ClipData.newPlainText("", text);
        cm.setPrimaryClip(mClipData);
        ToastHelper.show("复制成功");
    }

    /**
     * 设置透明状态栏（API21，5.0之后才能用）
     *
     * @param isLightMode 是否为亮色模式（黑色字体，需要6.0 以后支持，否则显示无效）
     */
    public static void requestTranslucentStatusBar(Activity activity, boolean isLightMode) {
        //大于6.0 并且是亮色模式
        if (isLightMode) {
            activity.getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        } else {
            activity.getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
        activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
    }

    /**
     * 判断是图片
     */
    public static boolean isImage(String path) {
        if (TextUtils.isEmpty(path)) {
            return false;
        }
        String mPath = path.toLowerCase();
        return mPath.endsWith("png")
                || mPath.endsWith("jpg")
                || mPath.endsWith("bmp")
                || mPath.endsWith("dib")
                || mPath.endsWith("jpeg")
                || mPath.endsWith("jfif")
                || mPath.endsWith("jpe")
                || mPath.endsWith("tif")
                || mPath.endsWith("tiff")
                || mPath.endsWith("gif")
                || mPath.endsWith("swf")
                || mPath.endsWith("webp")
                || mPath.endsWith("svg");
    }

    /**
     * 获取脱敏手机号  后四位****
     */
    public static String getStarPhone(String phoneNumber) {
        if (!TextUtils.isEmpty(phoneNumber) && phoneNumber.length() > 4) {
            return phoneNumber.substring(0, phoneNumber.length() - 4) + "****";
        }
        return phoneNumber;
    }

    /**
     * 判断一个字符串是否为数字
     */
    public static boolean isNumber(String str) {
        return str.matches("-?\\d+(\\.\\d+)?");
    }

    /**
     * 小数点0去掉
     */
    public static String getResultForDouble(double number) {
        String numberString = String.valueOf(number);
        if (numberString.contains(".")) {
            if (numberString.endsWith(".0")) {
                return numberString.substring(0, numberString.length() - 2);
            }
            int endIndex = numberString.length() - 1;
            for (int i = endIndex; i >= 0; i--) {
                char c = numberString.charAt(i);
                if (c != '0') {
                    endIndex = i;
                    break;
                }
            }
            return numberString.substring(0, endIndex + 1);
        } else {
            return numberString;
        }
    }
}